package com.infindo.iflower.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class FileUtil {
	public static String getSdcard() {
		String path = null;
		try {
			path = Environment.getExternalStorageDirectory().getPath();
		} catch (Exception e) {
			e.printStackTrace();
			path = "/sdcard";
		}
		return path;
	}

	public static boolean isSdPresent() {
		try {

			if (android.os.Environment.getExternalStorageState().equals(
					android.os.Environment.MEDIA_MOUNTED)) {
				File root = Environment.getExternalStorageDirectory();
				if (root.canWrite()) {
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
		return false;
	}

	public static boolean createDir(String path) {
		boolean ret = false;
		try {
			File file = new File(path);
			if (!file.isDirectory()) {
				ret = file.mkdirs();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static void delFilePath(String filepath) throws IOException {
		File f = new File(filepath);
		if (f.exists() && f.isDirectory()) {
			if (f.listFiles().length == 0) {
				f.delete();
			} else {
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						delFilePath(delFile[j].getAbsolutePath());
					}
					delFile[j].delete();
				}
			}
		}
	}

	public static void delFile(String filename) throws IOException {
		File f = new File(filename);
		if (f.exists() && !f.isDirectory()) {
			f.delete();

		}
	}

	public static String[] getsdfilenames(File files) {
		Vector<String> tempfilenames = new Vector<String>();
		String[] filenames = null;
		String paths = null;
		int num = 0;
		if (files != null) {
			paths = files.getAbsolutePath();
			File f = new File(paths);
			if (f.exists() && f.isDirectory()) {
				File readFile[] = f.listFiles();
				int k = f.listFiles().length;
				for (int j = 0; j < k; j++) {
					if (readFile[j].isDirectory()) {
						File getFile[] = readFile[j].listFiles();
						int len = readFile[j].listFiles().length;
						for (int m = 0; m < len; m++) {
							tempfilenames.add(getFile[m].getAbsolutePath());
							num++;
						}
					} else {
						tempfilenames.add(readFile[j].getAbsolutePath());
						num++;
					}
				}
			}

		}
		if (tempfilenames.size() > 0) {
			filenames = new String[tempfilenames.size()];
			for (int i = 0; i < tempfilenames.size(); i++) {
				filenames[i] = tempfilenames.elementAt(i);
			}
		}
		return filenames;
	}

	public static byte[] getBytesFromIS(InputStream is) throws IOException {
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		byte[] packet = new byte[1024];
		int numBytesRead = 0;

		while ((numBytesRead = is.read(packet)) != -1)
			buffer.write(packet, 0, numBytesRead);

		return buffer.toByteArray();

	}

	public static File existFile(String fileFullName) {

		File file = new File(fileFullName);
		if (file.exists() && file.isFile()) {
			return file;
		}

		return null;

	}

	public static boolean writeFile(String filePath, InputStream is) {
		FileOutputStream output;
		try {
			output = new FileOutputStream(filePath);

			// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
			byte[] packet = new byte[1024];
			int numBytesRead = 0;

			while ((numBytesRead = is.read(packet)) != -1) {
				output.write(packet);
				output.flush();
			}

			output.close();
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;

	}

	public static boolean writeFile(String filePath, InputStream is, int length) {
		FileOutputStream output;
		try {
			output = new FileOutputStream(filePath);
			int BUFFER_SIZE = 1024;
			// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
			byte[] packet = new byte[BUFFER_SIZE];
			int numBytesRead = 0;
			int downloaded = 0;

			while ((numBytesRead = is.read(packet)) != -1) {

				downloaded += packet.length;
				Log.e("down", "downloaded : " + downloaded
						+ "   packet length: " + packet.length);
				output.write(packet, 0, numBytesRead);
				output.flush();
				try {
					Thread.currentThread().sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (downloaded >= length) {
					break;
				} else if (downloaded + BUFFER_SIZE > length) {
					packet = new byte[length - downloaded];
				} else {
					packet = new byte[BUFFER_SIZE];
				}

			}
			// output.flush();

			/*
			 * while ((numBytesRead = is.read()) != -1) { downloaded ++;
			 * output.write(numBytesRead);
			 * 
			 * 
			 * if (downloaded >= 2048) { output.flush(); downloaded = 0;
			 * //break; } } output.flush();
			 */

			output.close();
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;

	}

	public static boolean writeFile(String filePath, byte[] bytes) {
		FileOutputStream output;
		try {
			output = new FileOutputStream(filePath);
			output.write(bytes);
			output.flush();
			output.close();
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;

	}

	public static Bitmap readBitmap(String filePath) {
		FileInputStream input;
		try {
			input = new FileInputStream(filePath);
			return BitmapFactory.decodeStream(input);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static boolean isValidFileName(String parent, String name) {
		if (parent == null || name == null) {
			return false;
		}

		File f = new File(parent, name);
		// if file already exists , it may be file name is correct
		if (!f.exists()) {
			try {
				boolean b = f.createNewFile();
				// if b is true , name is may be correct
				if (b) {
					// because the file is created for checking validity
					f.delete();
				}
				// if the new file's parent and the given parent is differ then
				// the file name is wrong
				if (!f.getParent().equals(parent)) {
					return false;
				}
				return b;
			} catch (IOException ioe) {
				return false;
			}
		}
		// if the new file's parent and the given parent is differ then the file
		// name is wrong
		return f.getParent().equals(parent);
	}

	public static Map<Integer, String> readfile(String filepath,
			Map<Integer, String> pathMap) throws Exception {
		if (pathMap == null) {
			pathMap = new HashMap<Integer, String>();
		}

		File file = new File(filepath);
		// is file
		if (!file.isDirectory()) {
			pathMap.put(pathMap.size(), file.getPath());

		} else if (file.isDirectory()) { // if directory, get all file
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(filepath + "/" + filelist[i]);
				if (!readfile.isDirectory()) {
					pathMap.put(pathMap.size(), readfile.getPath());

				} else if (readfile.isDirectory()) { // sub directory.
					readfile(filepath + "/" + filelist[i], pathMap);
				}
			}
		}
		return pathMap;
	}

	public static Map<Integer, String> readfileNoSub(String filepath,
			String suffix, Map<Integer, String> pathMap) throws Exception {
		if (pathMap == null) {
			pathMap = new HashMap<Integer, String>();
		}

		File file = new File(filepath);
		// is file
		if (!file.isDirectory()) {
			pathMap.put(pathMap.size(), file.getPath());

		} else if (file.isDirectory()) { // if directory, get all file
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(filepath + "/" + filelist[i]);
				if (!readfile.isDirectory()) {
					if (readfile.getPath().endsWith(suffix))
						pathMap.put(pathMap.size(), readfile.getPath());

				} else if (readfile.isDirectory()) { // sub directory.
					// readfile(filepath + "/" + filelist[i], pathMap);
				}
			}
		}
		return pathMap;
	}

	public static void writeBitmap(String filename, Bitmap bitmap) {
		try {
			if (bitmap != null) {
				FileOutputStream out = new FileOutputStream(filename);
				bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
